#define _CRT_SECURE_NO_WARNINGS 1

typedef int QDataType;

typedef struct QueueNode
{
	struct QueueNode* next;
	QDataType data;
}QNode;

typedef struct Queue
{
	QNode* head;
	QNode* tail;
	int size;
}Queue;

bool QueueEmpty(Queue* q)
{
	assert(q);
	return q->head == NULL && q->tail == NULL;//
}

void QueueInit(Queue* q)
{
	assert(q);
	q->head = q->tail = NULL;
	q->size = 0;
}

void QueuePush(Queue* q, QDataType x)
{
	assert(q);

	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc is fail");
		return;
	}
	newnode->data = x;//
	newnode->next = NULL;//
	if (q->head == NULL)
	{
		assert(q->tail == NULL);
		q->head = q->tail = newnode;
	}
	else
	{
		q->tail->next = newnode;
		q->tail = newnode;
	}
	q->size++;
}

void QueuePop(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));

	QNode* next = q->head->next;
	if (next == NULL)
	{
		free(q->head);
		q->head = q->tail = NULL;
	}
	else
	{
		free(q->head);
		q->head = next;
	}
	q->size--;
}

QDataType QueueFront(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));

	return q->head->data;
}

QDataType QueueBack(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));

	return q->tail->data;
}

int QueueSize(Queue* q)
{
	assert(q);
	return q->size;
}

void QueueDestroy(Queue* q)
{
	assert(q);

	QNode* cur = q->head;

	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	q->head == NULL;
	q->tail == NULL;
	q->size = 0;
}

typedef struct
{
	Queue q1;
	Queue q2;
} MyStack;

MyStack* myStackCreate()
{
	MyStack* obj = (MyStack*)malloc(sizeof(MyStack));
	if (obj == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	QueueInit(&obj->q1);
	QueueInit(&obj->q2);
	return obj;
}

void myStackPush(MyStack* obj, int x)
{
	if (!QueueEmpty(&obj->q1))
	{
		QueuePush(&obj->q1, x);
	}
	else
	{
		QueuePush(&obj->q2, x);
	}
}

int myStackPop(MyStack* obj)
{
	Queue* qEmpty = &obj->q1;
	Queue* qNonEmpty = &obj->q2;
	if (!QueueEmpty(qEmpty))
	{
		qEmpty = &obj->q2;
		qNonEmpty = &obj->q1;
	}

	while (QueueSize(qNonEmpty) > 1)
	{
		QueuePush(qEmpty, QueueFront(qNonEmpty));
		QueuePop(qNonEmpty);
	}
	int top = QueueFront(qNonEmpty);
	QueuePop(qNonEmpty);
	return top;
}

int myStackTop(MyStack* obj)
{
	Queue* qEmpty = &obj->q1;
	Queue* qNonEmpty = &obj->q2;
	if (!QueueEmpty(qEmpty))
	{
		qEmpty = &obj->q2;
		qNonEmpty = &obj->q1;
	}

	return QueueBack(qNonEmpty);
}

bool myStackEmpty(MyStack* obj)
{
	return QueueEmpty(&obj->q1) && QueueEmpty(&obj->q2);
}

void myStackFree(MyStack* obj) {
	QueueDestroy(&obj->q1);
	QueueDestroy(&obj->q2);

	free(obj);
}

/**
 * Your MyStack struct will be instantiated and called as such:
 * MyStack* obj = myStackCreate();
 * myStackPush(obj, x);

 * int param_2 = myStackPop(obj);

 * int param_3 = myStackTop(obj);

 * bool param_4 = myStackEmpty(obj);

 * myStackFree(obj);
*/